package org.insia.smartposse.mail;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.mail.BodyPart;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Message.RecipientType;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;

import org.apache.struts.upload.FormFile;

/**
 * Classe d'envois des messages
 * @author patrick
 * Project : Smartposse 
 * Class : org.insia.smartposse.mail
 * File : SmtpMail.java 
 * Created : 13 nov. 06 19:45:06
 */
/**
 * @author patrick
 * Project : Smartposse
 * Class : org.insia.smartposse.mail
 * File : SmtpMail.java
 * Created : Jan 14, 2007 10:23:58 AM
 */
/**
 * @author patrick
 * Project : Smartposse
 * Class : org.insia.smartposse.mail
 * File : SmtpMail.java
 * Created : Jan 14, 2007 10:24:05 AM
 */
public class SmtpMail {
    private final static String HOST = "mail.smtp.host";
    private Properties prop = new Properties();
    private Session session = null;
    private String adressFrom = null;
    private String[] adressTo = null;
    private MimeMessage msg = null;
    private BodyPart msgBody = null;
    private Multipart multiPart = null;
    private MailAuthentificator auth = null;

    /**
     * Constructeur
     * @param adressFrom
     * @param adressTo
     * @param mailHost
     */
    public SmtpMail(String adressFrom, String[] adressTo, String mailHost) {
        this.adressFrom = adressFrom;
        this.adressTo = adressTo;
        prop.put(HOST, mailHost);
    }

    /**
     * Constructeur
     * @param adressFrom
     * @param adressTo
     * @param mailHost
     * @param auth
     */
    public SmtpMail(String adressFrom, String[] adressTo, String mailHost,
                    MailAuthentificator auth) {
        this.adressFrom = adressFrom;
        this.adressTo = adressTo;
        prop.put(HOST, mailHost);
        this.auth = auth;
    }

    
    /**
     * Initialise la classe et l'envoi du message
     * @param Subject
     * @throws AddressException
     * @throws MessagingException
     */
    public void Initialize(String Subject) throws AddressException,
            MessagingException {
        if (auth != null) {
            prop.put("mail.smtp.auth", "true");
            prop.put("mail.smtps.auth", "true");
            session = Session.getInstance(prop, auth);
        } else {
            session = Session.getDefaultInstance(prop, auth);
        }
        msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(adressFrom));
        for (String recipient : adressTo) {
            msg.addRecipient(RecipientType.TO, new InternetAddress(recipient));
        }
        msg.setSubject(Subject);
    }

    
    /**
     * Configure le port smtp
     * @param port
     */
    public void setPortSmtp(int port) {
        prop.put("mail.smtp.port", String.valueOf(port));
        prop.put("mail.smtps.port", String.valueOf(port));
    }

    public void setHostSmtp(String host) {
        prop.put("mail.smtp.host", host);
        prop.put("mail.smtps.host", host);
    }

    /**
     * Met le message dans le mail en texte ou html
     * @param Body
     * @param Html
     * @throws MessagingException
     */
    public void setText(String Body, boolean Html) throws MessagingException {
        if (Html == true) {
            msg.setContent(Body, "text/html");
        } else {
            msg.setText(Body);
        }
    }

    /**
     * Fonction pour mettre du texte ou html avec une pièce jointe
     * @param Body
     * @param input
     * @param Html
     */
    public void setTextWithAttachedFiles(String Body, FormFile input,
                                         boolean Html) {
        try {
            msgBody = new MimeBodyPart();
            if (Html == true) {
                msgBody.setContent(Body, "text/html");
            } else {
                msgBody.setText(Body);
            }
            multiPart = new MimeMultipart();
            multiPart.addBodyPart(msgBody);
            msgBody = new MimeBodyPart();
            byte[] bytes = null;
            try {
                bytes = input.getFileData();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            ByteArrayDataSource dataSource = new ByteArrayDataSource(bytes,
                    input.getContentType());
            DataHandler dataHandler = new DataHandler(dataSource);
            msgBody.setDataHandler(dataHandler);
            msgBody.setFileName(input.getFileName());
            multiPart.addBodyPart(msgBody);
            msg.setContent(multiPart);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    /**
     * Envois le mail
     * @throws MessagingException
     */
    public void SendMail() throws MessagingException {
        Transport.send(msg);
    }

    /**
     * Envoie le mail sur un serveur avec du ssl
     * @throws MessagingException
     */
    public void SendMailSSL() throws MessagingException {
        Transport trans = session.getTransport("smtps");
        trans.connect(prop.getProperty(HOST), auth.getPasswordAuthentication()
                .getUserName(), auth.getPasswordAuthentication().getPassword());
        trans.sendMessage(msg, msg.getAllRecipients());
        trans.close();
    }

    
    /**
     * Retourne le message
     * @return le MimeMessage
     */
    public MimeMessage getMsg() {
        return msg;
    }

}
